<template>
  <div class="add-user">
    <el-form
      :inline="true"
      :rules="rules"
      ref="ruleForm"
      :model="dataForm"
      label-width="120px"
      class="dialog"
      :label-position="labelPosition"
      
    >
      <el-row :gutter="20">
        <el-col :span="12" style="position:relative">
          <el-form-item label="登录名称" prop="username">
            <el-input
              v-model="dataForm.username"
              placeholder="请输入登录名称"
              clearable
              :disabled="disabled"
              auto-complete="new-password"
            ></el-input>
          </el-form-item>
          <p
            style="color:#F56C6C;margin-left:130px;margin-bottom:20px;font-size:12px;position:absolute;left:0;top:45px;"
            v-if="validteGroupNo"
          >该登录名称已存在,请重新输入</p>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密 码" prop="password">
            <el-input v-model="dataForm.password"  placeholder="请输入密码" auto-complete="new-password" clearable show-password></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="dataForm.realName" placeholder="请输入真实姓名" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="mail">
            <el-input v-model="dataForm.mail" placeholder="请输入电子邮箱" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="dataForm.phone" placeholder="请输入电话" clearable></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="组织机构名称" prop="orgName">
            <el-input v-model="dataForm.orgName" placeholder="请输入组织机构名称" clearable></el-input>
          </el-form-item>
        </el-col> -->
                <el-col :span="12" v-if="isShowCompany">
          <el-form-item label="公司组名称" prop="companyCodes">
           <el-select v-model="dataForm.companyCodes" clearable placeholder="请输入公司组名称" :disabled="componydisabled" remote filterable @change="getCompanVal">
              <el-option
                v-for="item in companList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
           <!-- <el-col :span="12">
          <el-form-item label="用户类型">
            <el-select v-model="userTypeValue" placeholder="请选择" @change="selectUserType">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->

    
      </el-row>
      <el-row :gutter="20">
         <el-col :span="12">
          <el-form-item label="用户角色">
            <el-select v-model="dataForm.rolesCodes" clearable placeholder="请输入用户角色" :disabled="roledisabled" multiple>
              <el-option
                v-for="item in userRole"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="23">
            <el-form-item prop="remark" label="备注">
          <el-input type="textarea" :rows="5" placeholder="请输入备注" clearable v-model="dataForm.remark"></el-input>
        </el-form-item>
        </el-col>
      </el-row>
      <el-form-item style="margin-top:20px;margin-bottom:100px;text-align:center;">
       
        <el-button type="primary" @click="doneFinshed('ruleForm')" :disabled="isDabled">确认</el-button>
         <el-button type="info" @click="backPrev">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import md5 from 'md5'
export default {

  data () {
    var names = (rule, value, callback) => {
      var data = {
        name: this.dataForm.username
      }
      if (value == '') {
        callback(new Error('用户名不允许为空'))
      } else if (value && !this.noRepeat) {
        this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/user/checkOnly`, data).then((res) => {
          if (res.result) {
            this.noRepeat = res.data
            if (this.noRepeat == false) { // res.data.data [true]有重复/【false】无重复
              callback(new Error('该登录名称已存在,请重新输入'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    }
    var realName = (rule, value, callback) => {
      console.log(value)
    // value = value.replace(/[\d]/g, '')

      var regex = /^(([\u4e00-\u9fa5]{2,64})|([a-zA-Z]+\s?[a-zA-Z]+))$/
      if (value === '') {
        callback(new Error('真实姓名不允许为空'))
      } else if (!regex.test(value)) {
        callback(new Error('真实姓名只能输入中文或英文'))
      } else {
        callback()
      }
    }
    var phone = (rule, value, callback) => {
      if (value != '') {
        var regex = /^1\d{10}$/
        if (!regex.test(value)) {
          callback(new Error('请输入正确的电话'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      userRole: [],
      options: [],
      userTypeValue: '',
      validteGroupNo: false,
      disabled: false,
      multiple: false,
      noRepeat: false,
      dataForm: {
        rolesCodes: [],
        companyCodes: [],
        operateType: '',
        userType: '',
        username: '',
        password: '',
        realName: '',
        mail: '',
        phone: '',
        orgCode: '',
        orgNo: '',
        orgName: '',
        remark: ''

      },
      companList: [],
      roledisabled: false,
      componydisabled: false,
      labelPosition: 'right',
      sysCode: ['sys_role'],
      rules: {
        username: [
          { validator: names, required: true, trigger: 'blur' },
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不允许为空', trigger: 'blur' },
          { max: 20, message: '长度不可超过20个字符', trigger: 'blur' }
        ],
        realName: [
          { validator: realName, required: true, trigger: 'blur' },
          { min: 2, max: 64, message: '长度不可超过64个字符', trigger: 'blur' }
        ],
        phone: [
          { required: false, validator: phone, trigger: 'blur', type: 'number' },
          { max: 11, message: '长度不可超过11个字符', trigger: 'blur' }
        ],
        orgName: [
          { required: false, message: '请输入组织机构名称', trigger: 'blur' },
          { min: 2, max: 40, message: '长度不可超过40个字符', trigger: 'blur' }
        ],
        companyName: [
          { required: true, message: '请输入所属公司名称', trigger: 'blur' },
          { min: 2, max: 40, message: '长度不可超过40个字符', trigger: 'blur' }
        ],
        mail: [
          { required: false, message: '请输入正确的邮箱', trigger: 'blur', type: 'email' },
          { min: 2, max: 40, message: '长度不可超过40个字符', trigger: 'blur' }
        ],
        remark: [
          { min: 1, max: 255, message: '长度不可超过255个字符', trigger: 'blur' }
        ]
      },
      isShowCompany: true,
      isDabled: false,
      usernameInput: true
    }
  },
  mounted () {
    this.getDictionaryByType()
    this.getCompanList()
    this.getRoleOfUser()
    var companyCode = JSON.parse(localStorage.getItem('user_info')).a.companyCode
    console.log(companyCode)
    if (companyCode == null || companyCode == '') {
      this.isShowCompany = true
    } else {
      this.isShowCompany = false
    }
  },
  methods: {
    backPrev () {
      this.$router.go(-1)
    },
        // 检测用户名唯一性
    checkOnly (index) {
      console.log(111111)
      if (this.dataForm.username == '' && this.dataForm.username == '') {
        return
      }
      var data = {}
      if (index == 1) {
        data = {
          name: this.dataForm.username
        }
      } else {
        data = {
          name: this.dataForm.username
        }
      }
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/user/checkOnly`, data)
        .then(res => {
          if (res.result) {
            if (res.data) {
              if (index == 1) {
                this.validteGroupNo = false
              } else {
                this.validateName = false
              }
            } else {
              if (index == 1) {
                this.validteGroupNo = true
              } else {
                this.validateName = true
              }
            }
          }
        })
    },
    // 获取用户类型
    getDictionaryByType () {
      var data = {
        type: 'userType'
      }
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/dictionary/findDictionaryByType`, data).then((res) => {
        var result = res.data
        var delData = []
        if (res.result) {
          for (var k in result) {
            delData.push({value: result[k].dicCode, label: result[k].dicValue})
          }
          console.log(delData)
          this.options = delData
        }
      })
    },
    selectUserType () {
      if (this.userTypeValue === 'sys_user') {
        this.roledisabled = true
        this.componydisabled = false
        this.dataForm.companyCodes = []
        this.multiple = true
        this.getRoleOfUser(this.sysCode)
      } else {
        this.componydisabled = false
        this.roledisabled = true
        this.multiple = false
        this.dataForm.companyCodes = ''
      }
      this.dataForm.rolesCodes = []
    },
    getCompanVal () {
      console.log(this.dataForm.companyCodes)
      // if (this.userTypeValue === 'sys_user') {
      //   this.getRoleOfUser(this.dataForm.companyCodes)
      // } else {
      //   this.getRoleOfUser([this.dataForm.companyCodes])
      // }
      // if (this.dataForm.companyCodes.length > 0) {
      //   this.roledisabled = false
      // } else {
      //   this.roledisabled = true
      // }
    },
    getCompanList () {
      var data = {
        companyNo: '',
        name: ''
      }
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/companygroups/findCompanyGList`, data).then((res) => {
        var result = res.data
        var delData = []
        if (res.result) {
          for (var k in result) {
            delData.push({value: result[k].code, label: result[k].name})
          }
          this.companList = delData
        }
      })
    },
    doneFinshed (formName) {
      var groupName = ''
      for (var k in this.companList) {
        if (this.companList[k].value == this.dataForm.companyCodes) {
          groupName = this.companList[k].label
        }
      }
      var data = {
        rolesCodes: this.dataForm.rolesCodes,
        companyCodes: [this.dataForm.companyCodes],
        operateType: 'save',
        user: {
          username: this.dataForm.username,
          password: md5(this.dataForm.password),
          realName: this.dataForm.realName,
          mail: this.dataForm.mail,
          phone: this.dataForm.phone,
          orgCode: this.dataForm.orgCode,
          orgNo: this.dataForm.orgNo,
          orgName: this.dataForm.orgName,
          remark: this.dataForm.remark,
          comGroupCode: this.dataForm.companyCodes,
          comGroupName: groupName
        }
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.userTypeValue)
          // if (this.userTypeValue === 'sys_user') {
          //   if (this.dataForm.rolesCodes.length === 0) {
          //     this.$message({
          //       message: '请选择用户角色',
          //       type: 'warning'
          //     })
          //     return
          //   }
          // } else if (this.userTypeValue === 'company_user') {
          //   if (this.dataForm.companyCodes.length === 0) {
          //     this.$message({
          //       message: '请选择公司',
          //       type: 'warning'
          //     })
          //     return
          //   } else
          //   if (this.dataForm.rolesCodes.length === 0) {
          //     this.$message({
          //       message: '请选择用户角色',
          //       type: 'warning'
          //     })
          //     return
          //   }
          // }

          this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/user/operationData`, data).then((res) => {
            if (res.result) {
              this.isDabled = true
              this.$message({
                message: '操作成功',
                type: 'success'
              })

              this.$router.push('/systemSettings/user/list')
            } else {
              this.isDabled = false
              this.$message.error({
                message: res.msg,
                duration: 5000
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getRoleOfUser (code) {
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/user/findRoleOfUser`, { userCompanyCode: '' }).then((res) => {
        var data = res.data
        var delData = []
        for (var k in data) {
          delData.push({ value: data[k].code, label: data[k].name })
        }
        this.userRole = delData
      })
    }
  }
}
</script>
<style>
.dialog .el-form-item__content {
  width: 70%;
}
.dialog .el-form-item {
  width: 100%;
}
.dialog .el-select {
  width: 100%;
}
.el-form-item__label {
  text-align: right;
}

</style>

<style lang="scss" scoped>
.add-user {
  background: #fff;
  padding-top: 20px;
  padding-left: 20px;
}
</style>

